package com.yb.guigu.pick.activity.endpoint;

import com.yb.guigu.pick.activity.bean.WebsocketUser;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/7/16 13:55
 * FileName: BaseWebSocketEndpoint
 * Description:
 */
public abstract class BaseWebSocketEndpoint {

    /**
     * sessionId->user
     * @return
     */
    public abstract Map<String, WebsocketUser> getUserMap();


    /**
     * userId->Session
     * @return
     */
    public abstract Map<String, Session> getSessionMap();


    public  void addUser(WebsocketUser websocketUser,Session session){
        websocketUser.setSession(session);
        getSessionMap().put(websocketUser.getUserId(),session);
        getUserMap().put(session.getId(),websocketUser);
    }

    public  void addUser(WebsocketUser websocketUser){
        getUserMap().put(websocketUser.getSession().getId(),websocketUser);

    }

    public  WebsocketUser getUser(String sessionId){
        return getUserMap().get(sessionId );
    }

    public  WebsocketUser removeUser(String sessionId){

        WebsocketUser user = getUserMap().remove(sessionId);

        getSessionMap().remove(user.getUserId());

        return user;

    }

    public   void sendMsgBySessionId(String sessionId,String msg){
        WebsocketUser websocketUser = getUserMap().get(sessionId);

        if(Objects.isNull(websocketUser))return;

        try {
            websocketUser.getSession().getBasicRemote().sendText(msg);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public   void sendMsgByUserId(String userId,String msg){

        Session session = getSessionMap().get(userId);
        if(Objects.isNull(session))return;

        try {
            session.getBasicRemote().sendText(msg);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public  Collection<WebsocketUser> allUsers(){
        return getUserMap().values();
    }



    public  void sendAll(Collection<? extends  WebsocketUser> users,String msg){
        for (WebsocketUser user : users) {
            String userId = user.getUserId();
            try {
                user.getSession().getBasicRemote().sendText(msg);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public  void sendAll(String msg){
        sendAll(allUsers(),msg);
    }

}
